/*
* Copyright 2025 NXP
* NXP Proprietary. This software is owned or controlled by NXP and may only be used strictly in
* accordance with the applicable license terms. By expressly accepting such terms or by downloading, installing,
* activating and/or otherwise using the software, you are agreeing that you have read, and that you agree to
* comply with and are bound by, such license terms.  If you do not agree to be bound by the applicable license
* terms, then you may not retain, install, activate or otherwise use the software.
*/

#include "events_init.h"
#include <stdio.h>
#include <stdlib.h>
#include "ff.h" // FatFs 头文件
#include "lvgl.h"
#include "lv_demo.h" // 确保包含 draw_img 和 img_count 的声明

#if LV_USE_GUIDER_SIMULATOR && LV_USE_FREEMASTER
#include "freemaster_client.h"
#endif

// 定义txt文件路径数组
#define MAX_BOOK_FILES 25
static char book_file_paths[MAX_BOOK_FILES][32];
static uint8_t book_file_count = 0; // 当前小说文件索引
static uint8_t current_book_index = 0; 

// 定义txt文件行缓冲区大小
#define LINE_BUFFER_SIZE 360
#define BLOCK_SIZE 120 // 块大小，可以根据实际情况调整
static FIL current_book_file; // 当前打开的小说文件
static uint32_t current_line = 0; // 当前行号
static char current_line_content[LINE_BUFFER_SIZE]; // 当前行内容
static uint32_t last_click_time_next = 0;    // 上一次点击的时间
static uint32_t last_click_time_before = 0;    // 上一次点击的时间

// 定义图片路径数组
img_info_t draw_img[MAX_BOOK_FILES*2]; 
uint8_t img_count =0; // 当前存储的图片数量
static uint8_t current_image_index = 0; // 当前显示的图片索引
static uint32_t last_click_time_image = 0;    // 上一次点击的时间


/* 文件操作部分 */

// 遍历 SD 卡中的小说文件
void traverse_and_store_book_files(void) {
    FILINFO fno;
    DIR dir;
    FRESULT res;

    // 打开目录（假设小说文件存储在 "0:/STORY" 目录下）
    res = f_opendir(&dir, "0:/TEXT");
    if (res != FR_OK) {
        return;
    }

    // 遍历目录中的文件
    while (1) {
        res = f_readdir(&dir, &fno);
        if (res != FR_OK || fno.fname[0] == 0) break; // 结束遍历

//疑惑  // 跳过目录     
        if (fno.fattrib & AM_DIR) continue;

        // 筛选 TXT 文件
        if (strcmp(&fno.fname[strlen(fno.fname) - 4], ".txt") != 0) continue;

        // 构造完整路径
        sprintf(book_file_paths[book_file_count], "0:/TEXT/%s", fno.fname);

        book_file_count++;
    }
    f_closedir(&dir);
}


// 读取下一行
bool read_next_line(FIL *file, char *line_buffer, uint32_t buffer_size) {
    static char block[BLOCK_SIZE]; // 静态缓冲区，用于块读取
    static uint32_t block_pos = 0; // 当前块中已处理的位置
    static uint32_t block_len = 0; // 当前块中有效数据的长度
    uint32_t pos = 0; // 当前行缓冲区的位置

    while (1) 
	{
        // 如果块中没有剩余数据，则读取新的块
        if (block_pos >= block_len) 
		{
            FRESULT res;
            UINT bytes_read;
            res = f_read(file, block, BLOCK_SIZE, &bytes_read);
            if (res != FR_OK || bytes_read == 0) 
			{
                // 文件结束或读取错误
                if (pos == 0) {
                    return false; // 缓冲区为空，返回失败
                } else {
                    line_buffer[pos] = '\0';
                    return true; // 返回成功
                }
            }
            block_len = bytes_read;
            block_pos = 0;
        }

        // 从块中逐字节处理
        while (block_pos < block_len) 
		{
            char ch = block[block_pos++];
			
			// 这里只判断缓冲区是否已满，可以添加其他判断
			if (pos >= buffer_size - 1) 
			{
				line_buffer[pos] = '\0';
				return true; // 缓冲区已满，返回成功
			}
			line_buffer[pos++] = ch;
			
        }
    }
}


// 加载小说文件内容
bool load_book_file(uint8_t index) {
    if (index >= book_file_count) {
        return false;
    }

    // 关闭当前文件
    f_close(&current_book_file);

    // 打开文件
    FRESULT res = f_open(&current_book_file, book_file_paths[index], FA_READ);
    if (res != FR_OK) {
        return false;
    }

    return true;
}


// 读取下一行内容
bool read_next_line_content(char *line_buffer, uint32_t buffer_size) {
    if (!f_eof(&current_book_file)) {
        return read_next_line(&current_book_file, line_buffer, buffer_size);
    }
    return false;
}

// 读取指定行内容
bool read_specified_line_content(uint32_t line_number, char *line_buffer, uint32_t buffer_size) {
    f_close(&current_book_file);
    FRESULT res = f_open(&current_book_file, book_file_paths[current_book_index], FA_READ);
    if (res != FR_OK) {
        return false;
    }

    // 读取到指定行
    for (uint32_t i = 0; i < line_number; i++) {
        if (!read_next_line(&current_book_file, line_buffer, buffer_size)) {
            return false;
        }
    }

    return read_next_line(&current_book_file, line_buffer, buffer_size);
}


// 图片寻址处理部分
void traverse_and_store_bmp_files(void)
{
    FILINFO fno;
    DIR dir;
    FRESULT res;

    // 打开目录（假设目录路径是 "0:/PICTURE/BMP"）
    res = f_opendir(&dir, "0:/PICTURE/BMP");
    if (res != FR_OK) {
        return;
    }

    // 遍历目录中的文件
    while (1) {
        res = f_readdir(&dir, &fno);
        if (res != FR_OK || fno.fname[0] == 0) break; // 结束遍历

        // 筛选 BMP 文件
        if (fno.fattrib & AM_DIR) continue; // 跳过目录
        if (strcmp(&fno.fname[strlen(fno.fname) - 4], ".bmp") != 0) continue; // 只处理 BMP 文件

        // 计算路径长度
		size_t path_length = strlen("0:/PICTURE/BMP/") + strlen(fno.fname) + 1;  // +1 为 '\0'
		char *file_path = (char *)malloc(path_length);
        if (file_path == NULL) 
		{
            continue;
        }
        sprintf(file_path, "0:/PICTURE/BMP/%s", fno.fname);

        // 构造标签文本（这里简单使用文件名作为标签）
        char *label_text = (char *)malloc(strlen(fno.fname) + 1);
        if (label_text == NULL) {
            free(file_path);
            continue;
        }
        strcpy(label_text, fno.fname);

        // 存储到数组
        if (img_count < 100) {
            draw_img[img_count].img_path = file_path;
            draw_img[img_count].label_text = label_text;
            img_count++;
        } else {
            free(file_path);
            free(label_text);
            break;
        }
    }
    f_closedir(&dir);
}


/* 系统事件函数群 */

static void screen_main_Photos_event_handler (lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
	lv_ui *ui = (lv_ui *)lv_event_get_user_data(e); // 获取 ui
    switch (code) {
    case LV_EVENT_CLICKED:
    {
		ui_load_scr_animation(&guider_ui, &guider_ui.screen_photos, guider_ui.screen_photos_del, &guider_ui.screen_main_del, setup_scr_screen_photos, LV_SCR_LOAD_ANIM_FADE_ON, 50, 50, true, true);
		
		for (uint8_t i = 0; i < img_count; i++) 
		{
			if (draw_img[i].img_path != NULL) 
			{
				free((void *)draw_img[i].img_path);
				draw_img[i].img_path = NULL;
			}
			if (draw_img[i].label_text != NULL) 
			{
				free((void *)draw_img[i].label_text);
				draw_img[i].label_text = NULL;
			}
		}
		img_count = 0;
		current_image_index = 0;
		
		// 初始化图片文件列表
		traverse_and_store_bmp_files();
		lv_img_set_src(ui->screen_photos_Photos_r, draw_img[0].img_path);
		
        break;
    }
    default:
        break;
    }
}

static void screen_main_Book_event_handler (lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
	lv_ui *ui = (lv_ui *)lv_event_get_user_data(e); // 获取 ui
    switch (code) {
    case LV_EVENT_CLICKED:
    {
        ui_load_scr_animation(&guider_ui, &guider_ui.screen_book, guider_ui.screen_book_del, &guider_ui.screen_main_del, setup_scr_screen_book, LV_SCR_LOAD_ANIM_FADE_ON, 50, 50, true, true);
		
		traverse_and_store_book_files();
		// 如果有小说文件，加载第一本
		if (book_file_count > 0) 
		{
			load_book_file(0);
			if (read_specified_line_content(current_line, current_line_content, LINE_BUFFER_SIZE)) 
			{	
				lv_label_set_text(ui->screen_book_TXT_Label, current_line_content);
			}
		}
		else 
		{
            // 没有小说文件，给出提示
            lv_label_set_text(ui->screen_book_TXT_Label, "No books found");
        }
		
        break;
    }
    default:
        break;
    }
}

static void screen_photos_Photos_r_event_handler (lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    switch (code) {
    case LV_EVENT_CLICKED:
    {
        // 获取当前时间
        uint32_t current_time = lv_tick_get();
		
		// 检查时间
		if (current_time - last_click_time_image >= 2000) 
		{
			last_click_time_image = current_time; // 更新上一次点击时间
			
			// 更新图片索引，循环显示图片
			current_image_index++;
			if (current_image_index >= img_count) 
			{
				current_image_index = 0;
			}
			
			// 更新图片
			if (draw_img[current_image_index].img_path != NULL) 
			{
				lv_img_set_src(guider_ui.screen_photos_Photos_r, draw_img[current_image_index].img_path);
			}
		}
		
        break;
    }
    case LV_EVENT_LONG_PRESSED:
    {	
		ui_load_scr_animation(&guider_ui, &guider_ui.screen_main, guider_ui.screen_main_del, &guider_ui.screen_photos_del, setup_scr_screen_main, LV_SCR_LOAD_ANIM_NONE, 50, 50, true, true);
        break;
    }
    default:
        break;
    }
}

static void screen_book_Back_main_2_event_handler (lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    switch (code) {
    case LV_EVENT_CLICKED:
    {
		// 关闭当前小说文件
        f_close(&current_book_file);
        
        // 清除当前行内容缓冲区
        memset(current_line_content, 0, LINE_BUFFER_SIZE);
		
		// 加载主屏幕
		ui_load_scr_animation(&guider_ui, &guider_ui.screen_main, guider_ui.screen_main_del, &guider_ui.screen_book_del, setup_scr_screen_main, LV_SCR_LOAD_ANIM_NONE, 50, 50, true, true);
        break;
    }
    default:
        break;
    }
}

static void screen_book_Next_event_handler (lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
	
	lv_ui *ui = (lv_ui *)lv_event_get_user_data(e); // 获取 ui
	
    switch (code) {
    case LV_EVENT_CLICKED:
    {
        // 获取当前时间
        uint32_t current_time = lv_tick_get();
		
		// 检查时间
		if (current_time - last_click_time_next >= 1000) 
		{
			last_click_time_next = current_time; // 更新上一次点击时间
		
			// 读取下一行
			if (read_next_line_content(current_line_content, LINE_BUFFER_SIZE)) {
				lv_label_set_text(ui->screen_book_TXT_Label, current_line_content);
				current_line++;
			}
		
		}
        break;
    }
	case LV_EVENT_LONG_PRESSED:
    {
        // 切换小说的逻辑
        if (book_file_count > 0) {
            // 更新当前小说索引
            current_book_index++;
            if (current_book_index >= book_file_count) {
                current_book_index = 0; // 循环到第一本
            }

            // 加载新的小说文件
            if (load_book_file(current_book_index)) {
                // 重置当前行号
                current_line = 0;

                // 读取并显示新小说的第一行
                if (read_specified_line_content(current_line, current_line_content, LINE_BUFFER_SIZE)) {
                    lv_label_set_text(ui->screen_book_TXT_Label, current_line_content);
                }
            }
        }
        break;
    }
    default:
        break;
    }
}

static void screen_book_Before_event_handler (lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
	
	lv_ui *ui = (lv_ui *)lv_event_get_user_data(e); // 获取 ui
	
    switch (code) {
    case LV_EVENT_CLICKED:
    {
        // 获取当前时间
        uint32_t current_time = lv_tick_get();
		
		// 检查时间
		if (current_time - last_click_time_before >= 1000) 
		{
			last_click_time_before = current_time; // 更新上一次点击时间
			
			// 返回上一行
			if (current_line > 0) {
				current_line--;
				// 重新读取到指定行
				if (read_specified_line_content(current_line, current_line_content, LINE_BUFFER_SIZE)) {
					lv_label_set_text(ui->screen_book_TXT_Label, current_line_content);
				}
			}
		}
        break;
    }
    default:
        break;
    }
}

void events_init_screen_main (lv_ui *ui)
{
    lv_obj_add_event_cb(ui->screen_main_Photos, screen_main_Photos_event_handler, LV_EVENT_ALL, ui);
    lv_obj_add_event_cb(ui->screen_main_Book, screen_main_Book_event_handler, LV_EVENT_ALL, ui);
}

void events_init_screen_photos (lv_ui *ui)
{
    lv_obj_add_event_cb(ui->screen_photos_Photos_r, screen_photos_Photos_r_event_handler, LV_EVENT_ALL, ui);
}

void events_init_screen_book (lv_ui *ui)
{
    lv_obj_add_event_cb(ui->screen_book_Back_main_2, screen_book_Back_main_2_event_handler, LV_EVENT_ALL, ui);
    lv_obj_add_event_cb(ui->screen_book_Next, screen_book_Next_event_handler, LV_EVENT_ALL, ui);
    lv_obj_add_event_cb(ui->screen_book_Before, screen_book_Before_event_handler, LV_EVENT_ALL, ui);
}

void events_init(lv_ui *ui) {}




